package neuronet.client;

import java.net.Socket;

import org.apache.log4j.Logger;

public class ClientMessageThread extends Thread {

    // log4j-Logger
    private static Logger logger = Logger.getLogger(ClientMessageThread.class);

    // server ip and port
    private String serverURL;
    private int serverPort;
    private Socket socket;

    // clientid
    private String clientid;
    private String clientkey;

    // 
    NeuroNetClient neuroNetClient;

    public ClientMessageThread(String serverURL, int serverPort, String clientid)
    {
	this.serverPort = serverPort;
	this.serverURL = serverURL;
	this.clientid = clientid;

	initClient();
    }

    public ClientMessageThread(NeuroNetClient neuroNetClient)
    {
	this.neuroNetClient = neuroNetClient;
    }

    /**
     * The working method of the class Thread
     */
    public void run()
    {
	logger.info("Thread starting client " + clientid);
	while (true)
	{
	    logger.info("checking messages for " + clientid);
	    neuroNetClient.getData();
	    try
	    {
		Thread.sleep(3000);
	    }
	    catch (Exception e)
	    {
		logger.error("Error while " + clientid + " was sleeping.", e);
	    }

//	    logger.info("checking messages for " + clientid);
//		Random r = new Random();
//		String dataString = r.nextInt()+"," + r.nextDouble()+"," + r.nextInt()+ r.nextDouble() +"," + r.nextInt();
//		String send = "type:senddata clientid:" + clientid + " clientkey:" + clientkey + " data[" + dataString + "]" + " end:end";
//		String status = neuroNetClient.sendDataString(send);
//		logger.info("sendDataString in sendData() returned = " + status);
	}
    }

    /**
     * Method for initialization of client.
     */
    private void initClient()
    {
	try
	{
	    socket = new Socket(serverURL, serverPort);
	}
	catch (Exception e)
	{
	    logger.error("Error connecting to server:", e);
	    return;
	}
	logger.info("Connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
    }

    public void setClientkey(String clientkey)
    {
	this.clientkey = clientkey;
    }
}
